package com.example.service.impl;

import com.example.constant.RedisConstants;
import com.example.domain.LoginUser;
import com.example.service.LogoutService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LogoutServiceImpl implements LogoutService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public void logout() {
        // 获取SecurityContextHolder中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        Long id = user.getUser().getId();
        // 删除redis中的用户信息
        redisTemplate.delete(RedisConstants.USER_TOKEN + id);
        // 删除SecurityContextHolder中的用户信息
        SecurityContextHolder.clearContext();
    }

}
